package com.dongdongshop.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("file")
public class FileController {

	@RequestMapping("upLoadFile")
	@ResponseBody
	public Map<String,String> upLoadFile(@RequestParam(value = "myFile") MultipartFile myFile) {
		// 获取文件名
//		String fileName = "img/product/small/"+myFile.getOriginalFilename();
		String fileName = myFile.getOriginalFilename();
//		fileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
		// 上传文件的路径，就是文件需要保存的文件夹地址
//		String path = "/var/upload/";
		String path = "D:\\upload\\";
		// 构建一个文件
		File file = new File(path + fileName);
		// 调用上传方法，完成文件上传
		try {
			myFile.transferTo(file);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//{key:value}  @ResponseBody可以把实体类，list、Set，map、[{}] , {}
		Map<String,String> url = new HashMap<>();
		url.put("imgUrl", fileName);
		return url;
	}

//	@RequestMapping("download")
//	public ResponseEntity<byte[]> download(String filename) {
//		// 设置编码
//		try {
//			String newFileName = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
//			// 文件所在路径
////			String path = "/var/upload/";
//			String path = "D:\\upload\\";
////			String path = "D:\\upload\\";
//			// 文件下载的全路径
//			String downPath = path + filename;// E:\\upload\\abc.jsp
//			// 生成下载的文件
//			File file = new File(downPath);
//			// 设置HttpHeaders,使得浏览器响应下载
//			HttpHeaders headers = new HttpHeaders();
//			// 给浏览器设置下载文件名
//			headers.setContentDispositionFormData("attachment", newFileName);
//			// 浏览器响应方式
//			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//			// 把文件以二进制格式响应给浏览器
//			ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
//					headers, HttpStatus.OK);
//			return responseEntity;
//		} catch (Exception e) {
//			e.printStackTrace();
//			return null;
//		}
//	}
}
